import { Controller, Get, Post, Body, Ip, Headers, Request } from '@nestjs/common'
import * as Useragent from 'useragent'
import { createMath } from '@/utils/captcha'
import { GenerateUUID } from '@/utils/index'
import { ResultData } from '@/utils/result'
import { ConfigService } from '@nestjs/config'
import { RedisService } from '@/modules/redis/redis.service'
import { Public } from '@/common/decorators/public.decorator'
import { getIpAddress, getIp } from '@/utils/ip'
import { genCaptchaImgKey } from '@/utils/genKey'
import { AuthService } from './auth.service'
import { LoginDto } from './dto/index'

@Public()
@Controller('/')
export class AuthController {
	constructor(
		private readonly authService: AuthService,
		private readonly configService: ConfigService,
		private readonly redisService: RedisService
	) {}

	@Post('login')
	async login(@Body() loginDto: LoginDto, @Ip() ip: string, @Headers('user-agent') ua: string, @Request() req) {
		const agent = Useragent.parse(ua)
		const os = agent.os.toJSON().family
		const browser = agent.toAgent()
		const clientInfo = {
			ip: ip || getIp(req),
			os,
			ua,
			browser,
			loginTime: new Date().getTime(),
			loginLocation: '',
		}

		try {
			// 获取登录ip地址
			const address = await getIpAddress(clientInfo.ip)
			clientInfo.loginLocation = address
		} catch (error) {}
		// console.log('loginRes--', clientInfo)
		const loginRes = await this.authService.login(loginDto)

		// const loginLog = {
		// ..clientInfo,
		// 	username: userData.username,
		// 	userId: userData.id,
		// 	roles: userData.roles,
		// 	// permissions: permissions,
		// 	// deptId: userData.deptId,
		// }
		// this.loginlogService.create(loginLog) // 创建登录日志
		// console.log('loginRes--', loginRes)
		return loginRes
	}

	@Get('/captchaImage')
	async captchaImage() {
		//是否开启验证码
		const enabled = await this.configService.get<boolean>('app.captchaEnabled')
		const data = {
			enabled,
			img: '',
			text: '',
			uuid: '',
		}

		if (enabled) {
			const captchaInfo = createMath()
			data.img = captchaInfo.data
			data.text = captchaInfo.text.toLowerCase()
			data.uuid = GenerateUUID()
			// 验证码存入redis，有效期5分钟
			await this.redisService.setString(genCaptchaImgKey(data.uuid), captchaInfo.text.toLowerCase(), 1000 * 60 * 5)
		}

		return ResultData.success(data)
	}
}
